/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bluetoothproject;

import java.util.ArrayList;
import java.util.List;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;

/**
 *
 * @author lfournie
 */
public class Scan implements DiscoveryListener {

    private DiscoveryAgent agent;
    private ArrayList<RemoteClient> clients;
    private volatile boolean done = false;
    private JLabel label;
    private DefaultListModel listModel;

    public Scan(JLabel label, DefaultListModel listModel) throws BluetoothStateException {
        LocalDevice local = LocalDevice.getLocalDevice();
        agent = local.getDiscoveryAgent();
        this.label = label;
        this.listModel = listModel;

        clients = new ArrayList<RemoteClient>();

        System.out.println("Début de la recherche...");
        agent.startInquiry(DiscoveryAgent.GIAC, this);
/*
        synchronized (this) {
            try {
                this.wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
*/
            while(!done)
                ;
    }

    public void deviceDiscovered(RemoteDevice device, DeviceClass classe) {
        //System.out.println("----");

        try {
            /*System.out.println("nom : " + device.getFriendlyName(false));
            System.out.println("adresse : " + device.getBluetoothAddress());
            System.out.println();
            */
            RemoteClient r = new RemoteClient(device.getFriendlyName(false), device.getBluetoothAddress());
            clients.add(r);

            this.listModel.addElement(r);
            
        } catch (Exception e) {
            e.printStackTrace();
        }

        //System.out.println("----");

    }

    public void inquiryCompleted(int arg0) {
        this.label.setText("Recherche terminée");
        this.done = true;
    }

    public void serviceSearchCompleted(int arg0, int arg1) {
    }

    public void servicesDiscovered(int arg0, ServiceRecord[] arg1) {
    }

    public ArrayList<RemoteClient> getClients(){
        return this.clients;
    }
    
}
